var erpDataMap = {};
var truckDataMap = {};
var truckTeamArray = [];
var truckTableDom;
var erpTableDom;
var taskTableDom;
var bigErpTableDom;

var erpDataLoader = {
tempAddr:"",
newNormalData:function(){
    var timeType = erpDataLoader.getTimeType();
    var ioType = erpDataLoader.getIoType();
    var bigType = erpDataLoader.getBigType();
    var ziTuoType = erpDataLoader.getZiTuoType();
    var so_no = erpDataLoader.getso_no();
    var bigBizType = erpDataLoader.getBigBizType();
    var addrs = erpDataLoader.getAddrs();
    var d = {};
    d.erp_no = this.generateErpNo();
    d.p_erp_no = "";
    d.fen = 0;
    d.lockTruckTeam = "";
    d.truckNo = "";
    d.state="未确认";
    d.currentInSequence="否";
    d.timeType =timeType;
    d.ioType =ioType;
    d.bigType =bigType;
    d.ziTuoType =ziTuoType;
    
    var time = this.getsys_conf_current_time();
    if("提前下单"==timeType) {
        var ntime = new Date();
        ntime.setTime(getDate(time).getTime()+(24*3600*1000));
        d.customerTruckTime =d.actCustomerTruckTime = ntime.Format();
    }
    else {
        var ntime = new Date();
        ntime.setTime(getDate(time).getTime()+(6*3600*1000));
        d.customerTruckTime =d.actCustomerTruckTime = ntime.Format();
    }
    d.joinQueueTime ="";
    d.setTopTime ="";
    d.cn_type = "小";
    d.so_no = so_no;
    if("单一队列"==bigBizType) {
        d.addrs = addrs[0];
        this.tempAddr="";
    }
    else if("多队列"==bigBizType) {
        var addr =addrs[Math.round(Math.random())];
        if(this.tempAddr=="") {
            this.tempAddr=addr;
            d.addrs = addr;
        }
        else {
            d.addrs = this.tempAddr;
            this.tempAddr="";
        }
    } else if("混装模式"==bigBizType) {
        d.addrs =addrs[0]+" "+addrs[1];
        this.tempAddr="";
    }
    d.initAutoBizState = "是";
    d.initBigQueueId = "";
    d.initBigQueueSeq = "";
    d.initBigQueueGoFirst = "";
    return d;
},
generateFen:function(){
    return Math.round(100*Math.random());
},
    
generateErpNo: function(){
    return "E"+Math.round(100000000*Math.random());
},
generateTruckNo: function(){
    return "粤E"+Math.round(1000000*Math.random());
},
generateTruckTeamName: function(){
    return "车队"+Math.round(100*Math.random());
},
generateSo:function(){
    return "so"+Math.round(1000000*Math.random());
},
generateAddr:function(){
    return "广东省"+Math.round(1000000*Math.random());
},
generateBigQueueId:function(){
    return "T"+Math.round(1000000*Math.random());
},
getTimeType:function() {
    return $("input[name='timeType']:checked").val();
},
getIoType:function() {
    return $("input[name='ioType']:checked").val();
},
getBigType:function() {
    return $("input[name='bigType']:checked").val();
},
getZiTuoType:function() {
    return $("input[name='ziTuoType']:checked").val();
},
getsys_conf_auto_handle:function() {
    return $("input[name='sys_conf_auto_handle']:checked").val();
},
getsys_conf_current_time:function() {
    return $("#sys_conf_current_time").val();
},
setsys_conf_current_time:function(dateStr) {
    $("#sys_conf_current_time").val(dateStr);
},
getsys_conf_current_flush_time:function() {
    return $("#sys_conf_current_flush_time").val();
},
setsys_conf_current_flush_time:function(dateStr) {
    $("#sys_conf_current_flush_time").val(dateStr);
},
getsys_conf_current_fen_time_param:function() {
    return $("#sys_conf_current_fen_time_param").val();
},
getso_no:function(){
    return $($("#bigBizGenerateDiv input")[0]).val();
},
getBigBizType:function() {
    return $("input[name='bigBizType']:checked").val();
},
getAddrs:function() {
    var addrs = [];
    var inputs = $("#addrsGenerateDiv input").each(function(){
                                                   addrs.push($(this).val());
                                                   });
    return addrs;
},
loadTruck: function() {
    consoleTool.log("初始化车队");
    for(var i=0; i<3; i++) {
        var tname = this.generateTruckTeamName();
        truckTeamArray.push(tname);
        consoleTool.displayMsg(tname);
    }
    //var tempZiTuoTeam =truckTeamArray[Math.round(2*Math.random())];
    for(var i=0; i<10; i++) {
        var t = {};
        t.truckNo =this.generateTruckNo();
        t.truckTeam =truckTeamArray[Math.round(2*Math.random())];
        t.currentTask ="";
        t.currentTaskState ="";
        t.preTask ="";
        t.preTaskState ="";
        t.currentWorkState ="停运";
        t.currentInSequence ="否";
        t.lockState = Math.round(10*Math.random())>6?"否":"是";//tempZiTuoTeam==t.truckTeam?"纯自拖":"统一调度";
        t.joinQueueTime ="";
        t.currentInPort =Math.round(10*Math.random())>6?"是":"否";
        truckDataMap[t.truckNo] = t;
    }
    this.flushTruckTable();
},
flushErpTable: function(){
    erpTableDom.find("tr").each(function(){
                                if(this.firstChild.nodeName == "TD") {
                                this.parentNode.removeChild(this);
                                }
                                });
    for(d in erpDataMap) {
        var data = erpDataMap[d];
        var tds = [];
        for(a in data) {
            tds.push(data[a]);
        }
        var tr = this.newTR(tds);
        var id=Math.uuid();
        tr.attr("id",id);
        tr.attr("bizId",data.erp_no);
        erpTableDom.append(tr);
        this.bindErpTrContextMenu("#"+id);
    }
    this.flushBigErpTable();
},
flushTaskTable: function(){
    taskTableDom.find("tr").each(function(){
                                 if(this.firstChild.nodeName == "TD") {
                                 this.parentNode.removeChild(this);
                                 }
                                 });
    var seqMap = systemBiz.getTaskSequence();
    for(d in seqMap) {
        var data = seqMap[d];
        var tds = [];
        for(a in data) {
            tds.push(data[a]);
        }
        var tr = this.newTR(tds);
        var id=Math.uuid();
        tr.attr("id",id);
        tr.attr("bizId",data.erp_no);
        taskTableDom.append(tr);
        this.bindErpTrContextMenu("#"+id);
    }
},
flushBigErpTable: function(){
    bigErpTableDom.find("tr").each(function(){
                                   if(this.firstChild.nodeName == "TD") {
                                   this.parentNode.removeChild(this);
                                   }
                                   });
    var bigErpMap = systemBiz.getBigErps();
    for(d in bigErpMap) {
        var data = bigErpMap[d];
        var tds = [];
        for(a in data) {
            tds.push(data[a]);
        }
        var tr = this.newTR(tds);
        var id=Math.uuid();
        tr.attr("id",id);
        tr.attr("bizId",data.erp_no);
        bigErpTableDom.append(tr);
        this.bindErpTrContextMenu("#"+id);
    }
},
bindErpTrContextMenu: function(id) {
    $.contextMenu({
                  selector: id,
                  callback: function(key, options) {
                  //var m = "global: " + key;
                  //window.console && console.log(m) || alert(m);
                  },
                  items: {
                  "edit": {
                  name: "模拟拼单",
                  icon: "edit",
                  // superseeds "global" callback
                  callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  window.console && console.log(m) || alert(m);
                  
                  }
                  },
                  "setTaskToTop": {name: "任务置顶", icon: "copy",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setTaskToTop(m);
                  
                  }},
                  "unSetTaskToTop": {name: "取消置顶", icon: "delete",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.unSetTaskToTop(m);
                  
                  }},
                  "sep0": "---------",
                  "cut": {name: "取消拼单", icon: "cut"},
                  "copy": {name: "取消派单", icon: "copy"},
                  "cancelBiz": {name: "取消任务", icon: "cut"},"sep2": "---------",
                  "changeCustomerTruckTime": {name: "更改预约装柜时间［旺季当天装货失败，客户接受第二天装柜］", icon: "delete"},
                  "sep3": "---------",
                  "paste": {name: "大票单第一批任务进入队列", icon: "paste",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setBigBizIntoQueue(m);
                  
                  }},
                  "goBigBizFirst": {name: "大票单任务进入第一批", icon: "cut",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setTaskToBigBizFirst(m);
                  
                  }},
                  "setBigBizQueueAutoOn": {name: "大票单开启自动连续派单", icon: "paste",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setBigBizQueueAuto(m,"是");
                  
                  }},
                  "setBigBizQueueAutoOff": {name: "大票单取消自动连续派单", icon: "paste",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setBigBizQueueAuto(m,"否");
                  
                  }},
                  "forceTaskIntoQueue": {name: "手动控制任务进入队列", icon: "paste",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.forceTaskIntoQueue(m);
                  
                  }},
                  "sendTask": {name: "确认派单结果", icon: "delete"},
                  "sep1": "---------",
                  "quit": {name: "取消", icon: "quit"}
                  }
                  });
},
bindTruckTrContextMenu: function(id) {
    $.contextMenu({
                  selector: id,
                  callback: function(key, options) {
                  //var m = "global: " + key;
                  //window.console && console.log(m) || alert(m);
                  },
                  items: {
                  "edit": {
                  name: "启运",
                  icon: "edit",
                  // superseeds "global" callback
                  callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.setTruckActive(m);
                  
                  }
                  },"sep0": "---------",
                  "cut": {name: "停运", icon: "cut",
                  callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  window.console && console.log(m) || alert(m);
                  
                  }},"sep2": "---------",
                  "copy": {name: "确认任务", icon: "copy"},
                  "wczh": {name: "完成装货", icon: "edit",callback: function(key, options) {
                  var m = $(id).attr("bizId");
                  //window.console && console.log(m) || alert(m);
                  systemBiz.updateTruckTaskState(m,"完成装货");
                  
                  }},
                  "paste": {name: "车辆入闸/进入码头", icon: "paste"},
                  "tempUnlockTruck": {name: "临时解锁车辆", icon: "copy"},
                  //"delete": {name: "Delete", icon: "delete"},
                  "sep1": "---------",
                  "quit": {name: "取消", icon: "quit"}
                  }
                  });
},
flushTruckTable: function(){
    truckTableDom.find("tr").each(function(){
                                  if(this.firstChild.nodeName == "TD") {
                                  this.parentNode.removeChild(this);
                                  }
                                  });
    for(d in truckDataMap) {
        var data = truckDataMap[d];
        var tds = [];
        for(a in data) {
            tds.push(data[a]);
        }
        var tr = this.newTR(tds);
        truckTableDom.append(tr);
        var id=Math.uuid();
        tr.attr("id",id);
        tr.attr("bizId",data.truckNo);
        this.bindTruckTrContextMenu("#"+id);
    }
},
    newTR : function(tds) {
        var tr = $("<tr></tr>");
        for(var i=0; i<tds.length; i++) {
            var td =$("<td></td>");
            td.text(tds[i]);
            tr.append(td);
        }
        return tr;
    }
};

var consoleTool = {
    displayMsg : function(str){
        var currentStr =document.getElementById("console").innerHTML;
        document.getElementById("console").innerHTML = str;
        document.getElementById("console").innerHTML+="<br/>"+currentStr;
    },
log:function(str,showLog) {
    if(undefined==showLog || showLog)
        //this.displayMsg(new Date().Format()+"----"+str);
        this.displayMsg(erpDataLoader.getsys_conf_current_time()+"----"+str);
}
}

var clock;
$(function(){
  $("input[name='timeType']").get(0).checked=true;$("input[name='ioType']").attr("checked","0");$("input[name='bigType']").get(1).checked=true;$("input[name='ziTuoType']").attr("checked","0");
  $("input[name='sys_conf_auto_handle']").get(0).checked=true;
  $("#sys_conf_current_time").val(new Date().Format());
  $("#sys_conf_current_fen_time_param").val("1");
  $("input[name='bigBizType']").get(0).checked=true;
  bizButtonManager.initBigBizGenerateDiv();
  truckTableDom = $("#truckDataTable");
  erpTableDom = $("#erpDataTable");
  taskTableDom = $("#taskDataTable");
  bigErpTableDom = $("#bigBizDataTable");
  erpDataLoader.loadTruck();
  
  clock = setInterval("dynamicClock()",1000);
  });
function dynamicClock() {
    var currentDate = getDate(erpDataLoader.getsys_conf_current_time());
    var newDate = new Date();
    newDate.setTime(currentDate.getTime()+1000);
    erpDataLoader.setsys_conf_current_time(newDate.Format());
}
function goFastToFuture(minuteCount) {
    var currentDate = getDate(erpDataLoader.getsys_conf_current_time());
    var newDate = new Date();
    newDate.setTime(currentDate.getTime()+(minuteCount*60*1000));
    erpDataLoader.setsys_conf_current_time(newDate.Format());
}
function goFastToNext(time){
    var currentTime = erpDataLoader.getsys_conf_current_time();
    var atime = getDate(currentTime).Format("yyyy-MM-dd")+ " " + time;
    var newDate = new Date();
    if(getDate(currentTime).getTime()>getDate(atime).getTime()) {
        newDate.setTime(getDate(atime).getTime()+(24*3600*1000));
    }
    else {
        newDate.setTime(getDate(atime).getTime());
    }
    erpDataLoader.setsys_conf_current_time(newDate.Format());
    systemBiz.onTimeToHandleEarlyOrder();
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt)
{ //author: meizz
    var o = {
        "M+" : this.getMonth()+1,                 //月份
        "d+" : this.getDate(),                    //日
        "H+" : this.getHours(),                   //小时
        "m+" : this.getMinutes(),                 //分
        "s+" : this.getSeconds(),                 //秒
        "q+" : Math.floor((this.getMonth()+3)/3), //季度
        "S"  : this.getMilliseconds()             //毫秒
    };
    if(undefined==fmt||""==fmt) fmt="yyyy-MM-dd HH:mm:ss";
    if(/(y+)/.test(fmt))
        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
    return fmt;
}

//字符串转时间格式
function getDate(strDate) {
    var date = eval('new Date(' + strDate.replace(/\d+(?=-[^-]+$)/,
                                                  function (a) { return parseInt(a, 10) - 1; }).match(/\d+/g) + ')');
    return date;
}